using System;
using System.IO;

namespace EventLogMailer
{
    public class ApplicationState
    {
        public DateTime LastSentMail { get; set; }

        private const string MailerStateFileName = "mailer.state";
        

        public static void Save(ApplicationState applicationState)
        {
            try
            {
                Save(ExecutableRelativeStatePath, applicationState);
            }
            catch (Exception)
            {
                Save(ApplicationDataRelativeStatePath, applicationState);
            }
        }

        private static string ApplicationDataRelativeStatePath
        {
            get { return PathUtils.ResolveApplicationDataRelative(MailerStateFileName); }
        }

        private static void Save(string filePath, ApplicationState applicationState)
        {
            File.WriteAllText(filePath, Xml.Serialize(applicationState));
        }

        public static ApplicationState Load()
        {
            if (File.Exists(ExecutableRelativeStatePath))
            {
                return Load(ExecutableRelativeStatePath);
            }

            if (File.Exists(ApplicationDataRelativeStatePath))
            {
                return Load(ApplicationDataRelativeStatePath);
            }

            return new ApplicationState();
        }

        private static ApplicationState Load(string filePath)
        {
            var content = File.ReadAllText(filePath);
            return Xml.Deserialize<ApplicationState>(content);
        }

        private static string ExecutableRelativeStatePath
        {
            get { return PathUtils.ResolveApplicationExecutableRelative(MailerStateFileName); }
        }
    }
}